package sms

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"product/common/jwts"
	"strings"
)

type LuoSiMaoSms struct {
	BaseSms
}

// luoResult 调用螺丝短信响应参数
type luoResult struct {
	Status  LuoSiMaoProcessStatus `json:"error"`
	Message string                `json:"msg"`
	BatchId string                `json:"batch_id,omitempty"`
	Hit     string                `json:"hit,omitempty"`
}

func NewLuoSiMaoSms(userName, appKey, apiUrl string) *LuoSiMaoSms {
	return &LuoSiMaoSms{
		BaseSms: BaseSms{
			UserName: userName,
			AppKey:   appKey,
			ApiUrl:   apiUrl,
		},
	}
}

func (s *LuoSiMaoSms) SendSms(smsContent, mobile string) (bool, error) {
	valid, err := s.CheckInputValid(smsContent, mobile)
	if !valid {
		return false, err
	}
	status, err := s.httpPostRequest(map[string]interface{}{
		"mobile":  mobile,
		"message": smsContent,
	})
	if err != nil {
		return false, err
	}
	if status != LuoSuccess {
		return false, errors.New(status.ToLuoDescription())
	}
	return true, nil
}

func (s *LuoSiMaoSms) BatchSendSms(smsContent string, mobiles []string) (bool, error) {
	valid, err := s.CheckBatchInputValid(smsContent, mobiles)
	if !valid {
		return false, err
	}
	strTmp := strings.Join(mobiles, ",")
	fmt.Println("strTmp", strTmp)
	status, err := s.httpPostRequest(map[string]interface{}{
		"mobile_list": strTmp,
		"message":     smsContent,
	})
	if status != LuoSuccess {
		return false, errors.New(status.ToLuoDescription())
	}
	return true, nil
}

/**
私有方法
*/
// http请求处理
func (s *LuoSiMaoSms) httpPostRequest(params map[string]interface{}) (LuoSiMaoProcessStatus, error) {
	bytes, err := json.Marshal(params)
	if err != nil {
		return LuoOther, err
	}
	webClient := &http.Client{}
	req, err := http.NewRequest("POST", s.ApiUrl, strings.NewReader(string(bytes)))
	if err != nil {
		return LuoOther, err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", jwts.GenBaseAuth(s.UserName, s.AppKey))
	rest, err := webClient.Do(req)
	if err != nil {
		return LuoOther, err
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(rest.Body)
	response, _ := io.ReadAll(rest.Body)
	var result luoResult
	if err := json.Unmarshal(response, &result); err != nil {
		return LuoOther, err
	}
	fmt.Println("status", result.Status)
	return result.Status, nil
}
